<?php

namespace App\Http\Controllers\Admin;


use App\Models\Agency;
use App\Models\Device;
use App\Models\Grade;
use App\Models\Kind;
use App\Models\Type;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Matrix\Exception;

/**
 * 分类管理
 * Class AgencyController
 * @package App\Http\Controllers\Admin
 */
class AgencyDeviceController extends BaseController
{
    /**
     * 分类列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index($agency_id = null)
    {

        $agency = Agency::find($agency_id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        $list = $agency->Devices()->orderBy("id", "desc")->paginate(config('site.other.paginate'));

        $list->each(function (&$item){
            $grades = $item->grades()->pluck('name')->toArray();
            $item->grades = !empty($grades) ? $item->device = implode(',',$grades) : '';
        });

        return backendView('agencydevice.index', compact('list', 'agency'));
    }

    /**
     * 新增分类
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function add($agency_id, Request $request)
    {
        $agency = Agency::find($agency_id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }
        if ($request->isMethod("post")) {
            $this->validate($request, [
                'codes' => 'required|max:255',
                'kind_id' => 'required|exists:kinds,id',
                'get_time' => 'required|max:255',
            ], [], [
                'codes' => __("Code"),
                'kind_id' => '设备类型',
                'get_time' => '购买时间',
            ]);

            $data = $request->only(['codes', 'kind_id', 'get_time']);
            $data['agency_id'] = $agency_id;

            $request = Device::add($data);
            if ($request) {
                return redirect()->route('admin.agencydevice.index', ['agency_id' => $agency->id])->with('success', __('Create success'));
            }

            return back()->with('error', __('Create failed'))->withInput();
        } else {
            $kinds = Kind::where('status', 1)->get();
            //dd($type);
            return backendView('agencydevice.add', compact('kinds'));
        }
    }

    /**
     * 编辑分类
     * @param Request $request
     * @param null $id
     * @throws
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function edit(Request $request, $id = null)
    {
        /**
         * @var $device Device
         */
        $device = Device::find($id);
        if (empty($device)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($request->isMethod('POST')) {

            $this->validate($request, [
                'code' => 'required|max:255',
                'kind_id' => 'required|exists:kinds,id',
                'get_time' => 'required|max:255',
                'grade_id.*' =>'required|exists:grades,id'
            ], [], [
                'code' => __("Code"),
                'kind_id' => '设备类型',
                'get_time' => '购买时间',
                'grade_id' => '训练项目级别'
            ]);

            $data = $request->only(['code', 'kind_id', 'get_time', 'grade_id']);
            DB::beginTransaction();
            try {
                if (!$device->update($data)){
                    throw new \Exception("device update fail");
                }
                $device->deviceGrades()->delete();

                if (!empty($data['grade_id'])){
                    $insertData = [];
                    foreach ($data['grade_id'] as $v){
                        $insertData[] = ['grade_id'=>$v];
                    }
                    if (!$device->deviceGrades()->createMany($insertData)){
                        throw new \Exception("device grades create fail");
                    }
                }
                DB::commit();
                return redirect()->route('admin.agencydevice.index', ['agency_id' => $device->agency_id])->with('success', __('Edit success'));
            } catch (Exception $e){
                DB::rollBack();
                Log::error('device edit fail');
                Log::error($e);
                return back()->with('error', __('Edit failed'))->withInput();
            }

        } else {
            $kinds = Kind::where('status', 1)->get();
            $grades = Grade::all();
            $deviceGrades = $device->deviceGrades()->pluck('grade_id')->toArray();

            return backendView('agencydevice.edit', compact('device', 'kinds', 'grades', 'deviceGrades'));
        }
    }

    /**
     * 查看分类
     * @param null $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function view($id = null)
    {
        /**
         * @var $agency Agency
         */
        $device = Device::find($id);
        if (empty($device)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        return backendView('agencydevice.view', compact('device'));
    }

    /**
     * 删除分类
     * @param null $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delete($id = null)
    {
        /**
         * @var $agency Agency
         */
        $device = Device::find($id);
        if (empty($device)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        try {
            /*
                        $devices = $device->register()->get();
                        Log::error($devices);

                        if ( count($devices) > 0) {
                            return back()->with('error', '机构下有账户或设备，不能删除');
                        }
            */
            if ($device->delete()) {
                return back()->with('success', __('Delete success'));
            }
        } catch (\Exception $e) {
            Log::error('agency delete error:');
            Log::error($e->getMessage());
        }

        return back()->with('error', __('Delete failed'));
    }

    public function deviceadd($id = null, Request $request)
    {
        $agency = Agency::find($id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        if ($request->isMethod("post")) {
            $this->validate($request, [
                'codes' => 'required|max:255',
                'kind_id' => 'required|exists:kinds,id'
            ], [], [
                'codes' => __("Code"),
                'kind_id' => '设备类型'
            ]);

            $data = $request->only(['codes', 'kind_id']);
            $data['agency_id'] = $agency->id;

            if (true) {

                return redirect()->route('admin.agency.index')->with('success', '添加成功');
            }

            return back()->with('error', '添加失败')->withInput();
        }

        $kinds = Kind::where('status', 1)->get();
        return backendView('agency.device', compact('agency', 'kinds'));
    }

    /**
     * 机构设备列表
     * @param null $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function device($id)
    {
        $agency = Agency::find($id);
        if (empty($agency)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        $list = $agency->agencyDevices()->paginate(config('site.other.paginate'));

        return backendView('agency.devices', compact('list'));
    }

}